package com.mdd.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.service.IShopRecordService;
import com.mdd.admin.validate.ShopRecordCreateValidate;
import com.mdd.admin.validate.ShopRecordUpdateValidate;
import com.mdd.admin.validate.ShopRecordSearchValidate;
import com.mdd.admin.vo.ShopRecordListedVo;
import com.mdd.admin.vo.ShopRecordDetailVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.Shop;
import com.mdd.common.entity.ShopRecord;
import com.mdd.common.mapper.ShopMapper;
import com.mdd.common.mapper.ShopRecordMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 开店申请实现类
 * @author cxt
 */
@Service
public class ShopRecordServiceImpl implements IShopRecordService {
        
    @Resource
    ShopRecordMapper shopRecordMapper;

    @Resource
    ShopMapper shopMapper;

    /**
     * 开店申请列表
     *
     * @author cxt
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<ShopRecordListedVo>
     */
    @Override
    public PageResult<ShopRecordListedVo> list(PageValidate pageValidate, ShopRecordSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<ShopRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        shopRecordMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:userId@user_id:int",
            "like:shopName@shop_name:str",
            "like:shopCategory@shop_category:str",
            "like:contactName@contact_name:str",
            "=:phone:str",
            "like:userName@user_name:str",
            "=:password:str",
            "=:businessLicense@business_license:str",
            "=:isAgree@is_agree:int",
            "=:checkStatus@check_status:int",
            "=:checkUserId@check_user_id:long",
        });

        IPage<ShopRecord> iPage = shopRecordMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<ShopRecordListedVo> list = new LinkedList<>();
        for(ShopRecord item : iPage.getRecords()) {
            ShopRecordListedVo vo = new ShopRecordListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            vo.setBusinessLicense(UrlUtils.toAbsoluteUrl(item.getBusinessLicense()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 开店申请详情
     *
     * @author cxt
     * @param id 主键参数
     * @return ShopRecord
     */
    @Override
    public ShopRecordDetailVo detail(Integer id) {
        ShopRecord model = shopRecordMapper.selectOne(
                new QueryWrapper<ShopRecord>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        ShopRecordDetailVo vo = new ShopRecordDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 开店申请新增
     *
     * @author cxt
     * @param createValidate 参数
     */
    @Override
    public void add(ShopRecordCreateValidate createValidate) {
        ShopRecord model = new ShopRecord();
        model.setUserId(createValidate.getUserId());
        model.setShopName(createValidate.getShopName());
        model.setShopCategory(createValidate.getShopCategory());
        model.setContactName(createValidate.getContactName());
        model.setPhone(createValidate.getPhone());
        model.setUserName(createValidate.getUserName());
        model.setPassword(createValidate.getPassword());
        model.setBusinessLicense(createValidate.getBusinessLicense());
        model.setIsAgree(createValidate.getIsAgree());
        model.setCheckStatus(createValidate.getCheckStatus());
        model.setCheckUserId(createValidate.getCheckUserId());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setCreateTime(System.currentTimeMillis() / 1000);
        shopRecordMapper.insert(model);
    }

    /**
     * 开店申请编辑
     *
     * @author cxt
     * @param updateValidate 参数
     */
    @Override
    public void edit(ShopRecordUpdateValidate updateValidate) {
        ShopRecord model = shopRecordMapper.selectOne(
                new QueryWrapper<ShopRecord>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setUserId(updateValidate.getUserId());
        model.setShopName(updateValidate.getShopName());
        model.setShopCategory(updateValidate.getShopCategory());
        model.setContactName(updateValidate.getContactName());
        model.setPhone(updateValidate.getPhone());
        model.setUserName(updateValidate.getUserName());
        model.setPassword(updateValidate.getPassword());
        model.setBusinessLicense(updateValidate.getBusinessLicense());
        model.setIsAgree(updateValidate.getIsAgree());
        model.setCheckStatus(updateValidate.getCheckStatus());
        model.setCheckUserId(updateValidate.getCheckUserId());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        shopRecordMapper.updateById(model);
    }

    /**
     * 开店申请删除
     *
     * @author cxt
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        ShopRecord model = shopRecordMapper.selectOne(
                new QueryWrapper<ShopRecord>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        shopRecordMapper.delete(new QueryWrapper<ShopRecord>().eq("id", id));
    }

	@Override
	public void examine(ShopRecord record) {
		record.setUpdateTime(TimeUtils.timestamp());
        //如果审核通过就加入到商户表中
        if(record.getCheckStatus() == 1){
            Shop shop = new Shop();
            ShopRecord shopRecord = shopRecordMapper.selectById(record.getId());
            shop.setUserId(shopRecord.getUserId());
            shop.setName(shopRecord.getShopName());
            shop.setCreditScore(100);
            shop.setBusinessLicense("https://kdkdkd.oss-cn-shanghai.aliyuncs.com/" + shopRecord.getBusinessLicense());
            shop.setFans(0);
            shop.setCreateTime(TimeUtils.timestamp());
            shop.setUpdateTime(TimeUtils.timestamp());
            shop.setStatus(1);
            shop.setExtend2(record.getPhone());
            shopMapper.insert(shop);
        }
		shopRecordMapper.updateById(record);
	}

}
